<?php

class OperasiController extends Controller
{
	public function actionIndex($id=1)
	{
		//create division list
		$division = $this->createDivisionList();
		
		//create SKI model
		$model = new MonitoringOperasi('search');
		$model->unsetAttributes();
		if(isset($_GET['MonitoringOperasi'])) $model->attributes=$_GET['MonitoringOperasi'];
		
		//render
		$this->render('index',array('id'=>$id, 'division'=>$division, 'model'=>$model));
	}
	
	public function actionView($id)
	{
		$this->render('view',array('model'=>$this->loadModel($id)));
	}
	
	public function actionCreate($id)
	{
		//Initialize models
		$models = $this->initializeOperasiModels();
		
		//Ajax validation
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'operasi-form') {
            echo CActiveForm::validate($models);
            Yii::app()->end();
        }
        
		//Check POST
		if (isset($_POST['Transaksi'],$_POST['TransaksiAtribut'],
			$_POST['TransaksiOperasi'],$_POST['TransaksiKeteranganGagal']))
		{
			$models['transaksi']->attributes		 	= $_POST['Transaksi'];
			$models['transaksi_atribut']->attributes 	= $_POST['TransaksiAtribut'];
			$models['transaksi_operasi']->attributes	= $_POST['TransaksiOperasi'];
			$models['transaksi_gagal']->attributes	 	= $_POST['TransaksiKeteranganGagal'];
			
			//Validate
			$valid=$models['transaksi']->validate();
        	$valid=$models['transaksi_atribut']->validate() && $valid;
        	$valid=$models['transaksi_operasi']->validate() && $valid;
        	if ($models['transaksi']->id_status==2) $valid=$models['transaksi_gagal']->validate() && $valid;
        	
        	if ($valid) 
        	{
        		$models['transaksi']->save(false);
        		$models['transaksi_atribut']->save(false);
        		$models['transaksi_operasi']->save(false);
        		if ($models['transaksi']->id_status==2) $models['transaksi_gagal']->save(false);
        		
				$this->redirect(array('view','id'=>$models['transaksi']->id));
        	}
		}
		
		//Render
		$this->render('create',array('id'=>$id, 'models'=>$models));
	}
	
	public function actionUpdate($id)
	{
		//Initialize update models
		$transaksi=$this->loadModel($id);
		$atribut = $transaksi->transaksiAtributs;
		$operasi = $transaksi->transaksiOperasis;
		$gagal = null;
		if ($transaksi->id_status==2) {
			$gagal = $transaksi->transaksiKeteranganGagals;
		} else {
			$gagal =  new TransaksiKeteranganGagal();
			$gagal->id_transaksi = $transaksi->id;
		}
		
		$models = array(
			'transaksi'			=> $transaksi,
			'transaksi_atribut'	=> $atribut,
			'transaksi_operasi' => $operasi,
			'transaksi_gagal'	=> $gagal,
		);

		//Ajax validation
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'operasi-form') {
            echo CActiveForm::validate($models);
            Yii::app()->end();
        }
        
		//Check POST
		if (isset($_POST['Transaksi'],$_POST['TransaksiAtribut'],
			$_POST['TransaksiOperasi'],$_POST['TransaksiKeteranganGagal']))
		{
			$models['transaksi']->attributes		 	= $_POST['Transaksi'];
			$models['transaksi_atribut']->attributes 	= $_POST['TransaksiAtribut'];
			$models['transaksi_operasi']->attributes	= $_POST['TransaksiOperasi'];
			$models['transaksi_gagal']->attributes	 	= $_POST['TransaksiKeteranganGagal'];
			
			//Validate
			$valid=$models['transaksi']->validate();
        	$valid=$models['transaksi_atribut']->validate() && $valid;
        	$valid=$models['transaksi_operasi']->validate() && $valid;
        	if ($models['transaksi']->id_status==2) $valid=$models['transaksi_gagal']->validate() && $valid;
        	
        	if ($valid) 
        	{
        		$models['transaksi']->save(false);
        		$models['transaksi_atribut']->save(false);
        		$models['transaksi_operasi']->save(false);
        		if ($models['transaksi']->id_status==2) $models['transaksi_gagal']->save(false);
        		
				$this->redirect(array('view','id'=>$models['transaksi']->id));
        	}
		}
		
		//Render
		$this->render('update',array('id'=> $models['transaksi_operasi']->idPagu->id_divisi,'models'=>$models));
	}
	
	public function actionDelete($id)
	{			
		// we only allow deletion via POST request
		if(Yii::app()->request->isPostRequest)
		{
			//Load and delete
			$model = $this->loadModel($id);
			
			$model->transaksiAtributs->delete();
			$model->transaksiOperasis->delete();
			if ($model->id_status==2) $model->transaksiKeteranganGagals->delete();
			$model->delete();

			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	public function actionRequestPosList($divisi)
	{
		$array = $this->createPosList($divisi);
		$return_string = 'var retArray = new Array();';
		
		foreach ($array as $key => $value)
		{
			$return_string .= 'retArray[\''. $key .'\'] = "'. $value .'";';
		}
		echo $return_string;
	}
	
	public function actionRequestCurrentPagu($id)
	{
		//get pagu
		$pagu = Pagu::model()->findByPk($id);
		
		//get transactions
		$transaksis = $pagu->transaksiOperasis;
		$sum = 0;
		foreach ($transaksis as $transaksi) $sum += $transaksi->idTransaksi->nilai_rupiah;
		
		echo $pagu->nilai_rupiah - $sum;
	}
	
	public function getDivisionName($id) 
	{
		$query = "SELECT * FROM `spm_divisi` WHERE id=".$id;
		$command = Yii::app()->db->createCommand($query);
		$results = $command->query();
		
		if ($results->getRowCount()==1) 
		$row = $results->read();
		
		return $row['keterangan'];
	}
	
	public function createDivisionList()
	{
		$query = "SELECT * FROM `spm_divisi`";
		$command = Yii::app()->db->createCommand($query);
		$results = $command->query();
		
		//read
		$division = array();
		$division[] = "";
		
		$index = 1;
		foreach($results as $row) {
			$division[$index] = $row['nama'];
			$index++;
		}
		
		return $division;
	}
	
	//Create pos list from division id
	//return array with key = pagu id
	public function createPosList($id)
	{
		$list = array();
		
		$query = "SELECT spm_pagu.id AS id, spm_pos_keterangan.jenis_pos As pos, spm_pos_keterangan.keterangan
				AS keterangan FROM `spm_pagu` LEFT JOIN `spm_pos` ON spm_pagu.id_pos=spm_pos.id LEFT JOIN
				`spm_pos_keterangan` ON spm_pos.id_ket=spm_pos_keterangan.id WHERE spm_pagu.id_divisi=".$id;
		$command = Yii::app()->db->createCommand($query);
		$results = $command->query();
		
		foreach($results as $row) {
			$list[$row['id']] = $row['pos'].' - '.$row['keterangan'];
		}
		
		return $list;
	}
	
	private function loadModel($id)
	{
		$model=MonitoringOperasi::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	private function findLatestTransaksiID() 
	{
		$query = "SELECT * FROM `spm_transaksi` ORDER BY id DESC";
		$command = Yii::app()->db->createCommand($query);
		$results = $command->query();
		
		$row = $results->read();
		return $row['id'];
	}
	
	private function initializeOperasiModels()
	{
		//Find latest id
		$new_id = $this->findLatestTransaksiID();
		
		//Create transaksi model
		$transaksi = new Transaksi();
		$transaksi->id = $new_id+1;
		$transaksi->id_jenis = 1;
		$transaksi->id_status = 1;
		
		//Create transaksi atribut model
		$atribut = new TransaksiAtribut();
		$atribut->id_transaksi = $transaksi->id;
		
		//Create transaksi Operasi model
		$operasi = new TransaksiOperasi();
		$operasi->id_transaksi = $transaksi->id;
		
		//Create transaksi gagal model
		$gagal = new TransaksiKeteranganGagal();
		$gagal->id_transaksi = $transaksi->id;
		
		//Insert all into array
		$models = array(
			'transaksi'			=> $transaksi,
			'transaksi_atribut'	=> $atribut,
			'transaksi_operasi'	=> $operasi,
			'transaksi_gagal'	=> $gagal,
		);
		
		//return
		return $models;
	}
}